<!DOCTYPE html>
<html lang="zh-CN">
{% load static %}
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>发票列表</title>
    <!-- 引用本地static目录下的bootstrap.min.css文件 -->
    <link rel="stylesheet" href="{% static 'css/bootstrap.min.css' %}">
    <link rel="stylesheet" href="{% static 'css/bootstrap-icons.css' %}">
    <link rel="stylesheet" href="{% static 'css/pagination.css' %}">
    <script src="{% static 'js/vue.global.js' %}"></script>
    <script src="{% static 'js/axios.min.js' %}"></script>
    <script src="{% static 'js/pagination.js' %}"></script>
</head>
{% verbatim %}
<body>

<div id="app" class="container-fluid">
  <!-- 搜索栏 -->
  <div class="border rounded p-3 mb-3">
    <form class="row g-3 align-items-center">
      <div class="col-auto">
        <input type="text" class="form-control" placeholder="请输入发票号码" v-model="searchForm.invoice_code">
      </div>
      <div class="col-auto">
        <input type="text" class="form-control" placeholder="请输入用户姓名" v-model="searchForm.user_name">
      </div>
      <div class="col-auto">
        <input type="date" class="form-control" placeholder="开始日期" v-model="searchForm.start_date">
      </div>
      <div class="col-auto">
        <span class="mx-1">至</span>
      </div>
      <div class="col-auto">
        <input type="date" class="form-control" placeholder="结束日期" v-model="searchForm.end_date">
      </div>
      <div class="col-auto">
        <button type="button" class="btn btn-primary" @click="onSearch">搜索</button>
        <button type="button" class="btn btn-secondary ms-2" @click="resetSearch">重置</button>
      </div>
    </form>
  </div>

  <!-- 操作按钮栏 -->
  <div class="border rounded p-2 mb-3 d-flex align-items-center gap-2">
    <button class="btn btn-primary btn-sm" @click="viewDetail">
      <i class="bi bi-file-text"></i> 详情
    </button>
    <button class="btn btn-info btn-sm" @click="viewInvoice">
      <i class="bi bi-eye"></i> 发票阅览
    </button>
    <button class="btn btn-success btn-sm" @click="exportData">
      <i class="bi bi-download"></i> 导出
    </button>
  </div>

  <!-- 表格 -->
  <div class="rounded p-2">
    <table class="table table-bordered table-hover align-middle mb-0">
      <thead class="table-light">
        <tr>
          <th scope="col" width="60">
            <input type="checkbox" v-model="selectAll" @change="toggleAll">
          </th>
          <th scope="col" width="80">ID编号</th>
          <th scope="col" width="200">发票号码</th>
          <th scope="col" width="150">发票类型</th>
          <th scope="col" width="120">合计金额</th>
          <th scope="col" width="120">价税合计</th>
          <th scope="col" width="120">开票日期</th>
          <th scope="col">购买方</th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="item in invoiceList" :key="item.id">
          <td><input type="checkbox" v-model="item.selected"></td>
          <td>{{ item.id }}</td>
          <td>{{ item.invoice_code || '-' }}</td>
          <td>{{ item.invoice_type || '-' }}</td>
          <td class="text-end">{{ formatMoney(item.total_amount) }}</td>
          <td class="text-end">{{ formatMoney(item.total_price_tax) }}</td>
          <td>{{ formatDate(item.issue_date) }}</td>
          <td>{{ item.buyer_name || '-' }}</td>
        </tr>
        <tr v-if="invoiceList.length === 0">
          <td colspan="8" class="text-center text-muted py-4">暂无数据</td>
        </tr>
      </tbody>
    </table>
  </div>

  <!-- 加载提示 -->
  <div v-if="loading" class="text-center py-4">
    <div class="spinner-border text-primary" role="status">
      <span class="visually-hidden">Loading...</span>
    </div>
  </div>

  <!-- 发票详情模态框 -->
  <div class="modal fade" :class="{show: detailModal.visible}" tabindex="-1" :style="detailModal.visible ? 'display:block;background:rgba(0,0,0,0.5);' : ''">
    <div class="modal-dialog modal-xl modal-dialog-centered modal-dialog-scrollable">
      <div class="modal-content">
        <div class="modal-header">
          <h5 class="modal-title">发票详情</h5>
          <button type="button" class="btn-close" @click="closeDetailModal"></button>
        </div>
        <div class="modal-body">
          <div v-if="detailLoading" class="text-center py-5">
            <div class="spinner-border text-primary" role="status">
              <span class="visually-hidden">加载中...</span>
            </div>
          </div>
          <div v-else-if="invoiceDetail" class="container-fluid">
            <!-- 发票基本信息 -->
            <h6 class="border-bottom pb-2 mb-3">发票基本信息</h6>
            <div class="row mb-3">
              <div class="col-md-6">
                <div class="row mb-2">
                  <label class="col-sm-4 col-form-label text-end">发票类型：</label>
                  <div class="col-sm-8">
                    <input type="text" class="form-control" :value="invoiceDetail.invoice_type || ''" readonly style="background-color: #e9ecef; cursor: not-allowed;">
                  </div>
                </div>
              </div>
              <div class="col-md-6">
                <div class="row mb-2">
                  <label class="col-sm-4 col-form-label text-end">发票代码：</label>
                  <div class="col-sm-8">
                    <input type="text" class="form-control" :value="invoiceDetail.invoice_code || ''" readonly style="background-color: #e9ecef; cursor: not-allowed;">
                  </div>
                </div>
              </div>
            </div>
            <div class="row mb-3">
              <div class="col-md-6">
                <div class="row mb-2">
                  <label class="col-sm-4 col-form-label text-end">开票日期：</label>
                  <div class="col-sm-8">
                    <input type="text" class="form-control" :value="formatDate(invoiceDetail.issue_date)" readonly style="background-color: #e9ecef; cursor: not-allowed;">
                  </div>
                </div>
              </div>
              <div class="col-md-6">
                <div class="row mb-2">
                  <label class="col-sm-4 col-form-label text-end">开票人：</label>
                  <div class="col-sm-8">
                    <input type="text" class="form-control" :value="invoiceDetail.drawer || ''" readonly style="background-color: #e9ecef; cursor: not-allowed;">
                  </div>
                </div>
              </div>
            </div>

            <!-- 购买方信息 -->
            <h6 class="border-bottom pb-2 mb-3 mt-4">购买方信息</h6>
            <div class="row mb-3">
              <div class="col-md-6">
                <div class="row mb-2">
                  <label class="col-sm-4 col-form-label text-end">购买方名称：</label>
                  <div class="col-sm-8">
                    <input type="text" class="form-control" :value="invoiceDetail.buyer_name || ''" readonly style="background-color: #e9ecef; cursor: not-allowed;">
                  </div>
                </div>
              </div>
              <div class="col-md-6">
                <div class="row mb-2">
                  <label class="col-sm-4 col-form-label text-end">纳税人识别号：</label>
                  <div class="col-sm-8">
                    <input type="text" class="form-control" :value="invoiceDetail.buyer_tax_id || ''" readonly style="background-color: #e9ecef; cursor: not-allowed;">
                  </div>
                </div>
              </div>
            </div>
            <div class="row mb-3">
              <div class="col-md-6">
                <div class="row mb-2">
                  <label class="col-sm-4 col-form-label text-end">地址电话：</label>
                  <div class="col-sm-8">
                    <input type="text" class="form-control" :value="invoiceDetail.buyer_address_phone || ''" readonly style="background-color: #e9ecef; cursor: not-allowed;">
                  </div>
                </div>
              </div>
              <div class="col-md-6">
                <div class="row mb-2">
                  <label class="col-sm-4 col-form-label text-end">开户行及账号：</label>
                  <div class="col-sm-8">
                    <input type="text" class="form-control" :value="invoiceDetail.buyer_bank_account || ''" readonly style="background-color: #e9ecef; cursor: not-allowed;">
                  </div>
                </div>
              </div>
            </div>

            <!-- 销售方信息 -->
            <h6 class="border-bottom pb-2 mb-3 mt-4">销售方信息</h6>
            <div class="row mb-3">
              <div class="col-md-6">
                <div class="row mb-2">
                  <label class="col-sm-4 col-form-label text-end">销售方名称：</label>
                  <div class="col-sm-8">
                    <input type="text" class="form-control" :value="invoiceDetail.seller_name || ''" readonly style="background-color: #e9ecef; cursor: not-allowed;">
                  </div>
                </div>
              </div>
              <div class="col-md-6">
                <div class="row mb-2">
                  <label class="col-sm-4 col-form-label text-end">纳税人识别号：</label>
                  <div class="col-sm-8">
                    <input type="text" class="form-control" :value="invoiceDetail.seller_tax_id || ''" readonly style="background-color: #e9ecef; cursor: not-allowed;">
                  </div>
                </div>
              </div>
            </div>
            <div class="row mb-3">
              <div class="col-md-6">
                <div class="row mb-2">
                  <label class="col-sm-4 col-form-label text-end">地址电话：</label>
                  <div class="col-sm-8">
                    <input type="text" class="form-control" :value="invoiceDetail.seller_address_phone || ''" readonly style="background-color: #e9ecef; cursor: not-allowed;">
                  </div>
                </div>
              </div>
              <div class="col-md-6">
                <div class="row mb-2">
                  <label class="col-sm-4 col-form-label text-end">开户行及账号：</label>
                  <div class="col-sm-8">
                    <input type="text" class="form-control" :value="invoiceDetail.seller_bank_account || ''" readonly style="background-color: #e9ecef; cursor: not-allowed;">
                  </div>
                </div>
              </div>
            </div>

            <!-- 项目明细 -->
            <h6 class="border-bottom pb-2 mb-3 mt-4">项目明细</h6>
            <div class="table-responsive">
              <table class="table table-bordered table-sm">
                <thead class="table-light">
                  <tr>
                    <th width="30">序号</th>
                    <th>货物/服务名称</th>
                    <th>规格型号</th>
                    <th>单位</th>
                    <th>数量</th>
                    <th>单价</th>
                    <th>金额</th>
                    <th>税率</th>
                    <th>税额</th>
                  </tr>
                </thead>
                <tbody>
                  <tr v-for="(item, index) in invoiceDetail.items" :key="item.id">
                    <td>{{ index + 1 }}</td>
                    <td>{{ item.item_name || '-' }}</td>
                    <td>{{ item.specification || '-' }}</td>
                    <td>{{ item.unit || '-' }}</td>
                    <td class="text-end">{{ item.quantity || '-' }}</td>
                    <td class="text-end">{{ formatMoney(item.unit_price) }}</td>
                    <td class="text-end">{{ formatMoney(item.amount) }}</td>
                    <td class="text-center">{{ item.tax_rate || '-' }}</td>
                    <td class="text-end">{{ formatMoney(item.tax_amount) }}</td>
                  </tr>
                  <tr v-if="!invoiceDetail.items || invoiceDetail.items.length === 0">
                    <td colspan="9" class="text-center text-muted">暂无明细数据</td>
                  </tr>
                </tbody>
              </table>
            </div>

            <!-- 合计信息 -->
            <h6 class="border-bottom pb-2 mb-3 mt-4">合计信息</h6>
            <div class="row mb-3">
              <div class="col-md-4">
                <div class="row mb-2">
                  <label class="col-sm-5 col-form-label text-end">合计金额：</label>
                  <div class="col-sm-7">
                    <input type="text" class="form-control" :value="formatMoney(invoiceDetail.total_amount)" readonly style="background-color: #e9ecef; cursor: not-allowed;">
                  </div>
                </div>
              </div>
              <div class="col-md-4">
                <div class="row mb-2">
                  <label class="col-sm-5 col-form-label text-end">合计税额：</label>
                  <div class="col-sm-7">
                    <input type="text" class="form-control" :value="formatMoney(invoiceDetail.total_tax)" readonly style="background-color: #e9ecef; cursor: not-allowed;">
                  </div>
                </div>
              </div>
              <div class="col-md-4">
                <div class="row mb-2">
                  <label class="col-sm-5 col-form-label text-end">价税合计：</label>
                  <div class="col-sm-7">
                    <input type="text" class="form-control" :value="formatMoney(invoiceDetail.total_price_tax)" readonly style="background-color: #e9ecef; cursor: not-allowed;">
                  </div>
                </div>
              </div>
            </div>

            <!-- 其他信息 -->
            <h6 class="border-bottom pb-2 mb-3 mt-4">其他信息</h6>
            <div class="row mb-3">
              <div class="col-md-6">
                <div class="row mb-2">
                  <label class="col-sm-4 col-form-label text-end">校验码：</label>
                  <div class="col-sm-8">
                    <input type="text" class="form-control" :value="invoiceDetail.check_code || ''" readonly style="background-color: #e9ecef; cursor: not-allowed;">
                  </div>
                </div>
              </div>
              <div class="col-md-6">
                <div class="row mb-2">
                  <label class="col-sm-4 col-form-label text-end">机器编号：</label>
                  <div class="col-sm-8">
                    <input type="text" class="form-control" :value="invoiceDetail.machine_code || ''" readonly style="background-color: #e9ecef; cursor: not-allowed;">
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-secondary" @click="closeDetailModal">关闭</button>
        </div>
      </div>
    </div>
  </div>

  <!-- 发票图片阅览模态框 -->
  <div class="modal fade" :class="{show: imageModal.visible}" tabindex="-1" :style="imageModal.visible ? 'display:block;background:rgba(0,0,0,0.5);' : ''">
    <div class="modal-dialog modal-xl modal-dialog-centered">
      <div class="modal-content">
        <div class="modal-header">
          <h5 class="modal-title">发票图片阅览</h5>
          <button type="button" class="btn-close" @click="closeImageModal"></button>
        </div>
        <div class="modal-body">
          <div v-if="imageLoading" class="text-center py-5">
            <div class="spinner-border text-primary" role="status">
              <span class="visually-hidden">加载中...</span>
            </div>
          </div>
          <div v-else-if="invoiceImage" class="text-center">
            <!-- 发票信息 -->
            <div class="mb-3">
              <span class="badge bg-secondary me-2">发票号码: {{ invoiceImage.invoice_code || '-' }}</span>
            </div>
            <!-- 图片展示 -->
            <div class="invoice-image-container">
              <img :src="invoiceImage.image_url" 
                   alt="发票图片" 
                   class="img-fluid" 
                   style="max-width: 100%; max-height: 70vh; border: 1px solid #dee2e6; border-radius: 4px;"
                   @error="handleImageError">
            </div>
            <!-- 图片操作按钮 -->
            <div class="mt-3">
              <a :href="invoiceImage.image_url" 
                 target="_blank" 
                 class="btn btn-sm btn-outline-primary me-2">
                <i class="bi bi-arrows-fullscreen"></i> 全屏查看
              </a>
              <a :href="invoiceImage.image_url" 
                 download 
                 class="btn btn-sm btn-outline-success">
                <i class="bi bi-download"></i> 下载图片
              </a>
            </div>
          </div>
          <div v-else class="text-center py-5 text-muted">
            暂无图片数据
          </div>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-secondary" @click="closeImageModal">关闭</button>
        </div>
      </div>
    </div>
  </div>
</div>

<script>
const { createApp, ref, reactive, onMounted } = Vue;

const app = createApp({
  setup() {
    // 数据状态定义
    const invoiceList = ref([]);
    const loading = ref(false);
    const selectAll = ref(false);
    const detailLoading = ref(false);
    const invoiceDetail = ref(null);
    const imageLoading = ref(false);
    const invoiceImage = ref(null);
    
    // 详情模态框状态
    const detailModal = reactive({
      visible: false
    });
    
    // 图片阅览模态框状态
    const imageModal = reactive({
      visible: false
    });
    
    // 搜索表单
    const searchForm = reactive({
      invoice_code: '',
      user_name: '',
      start_date: '',
      end_date: ''
    });

    // 查询受票列表
    const queryList = () => {
      loading.value = true;
      axios({
        url: '/api/invoice/query_invoices',
        method: 'post',
        data: searchForm
      }).then(res => {
        console.log('响应数据:', res.data);
        loading.value = false;
        
        // 兼容多种响应格式
        if (res.data && (res.data.code === 200 || res.status === 200)) {
          let data = res.data.data || [];
          // 为每条数据添加selected属性
          invoiceList.value = data.map(item => ({
            ...item,
            selected: false
          }));
          console.log('发票列表数据:', invoiceList.value);
        } else {
          console.error('查询失败:', res.data.message || '未知错误');
          alert('查询失败: ' + (res.data.message || '请检查服务器连接'));
        }
      }).catch(err => {
        loading.value = false;
        console.error('请求失败:', err);
        alert('请求失败，请检查网络连接');
      });
    };

    // 搜索
    const onSearch = () => {
      console.log('搜索条件:', searchForm);
      queryList();
    };

    // 重置搜索
    const resetSearch = () => {
      searchForm.invoice_code = '';
      searchForm.user_name = '';
      searchForm.start_date = '';
      searchForm.end_date = '';
      queryList();
    };

    // 全选/反选
    const toggleAll = () => {
      invoiceList.value.forEach(item => {
        item.selected = selectAll.value;
      });
    };

    // 查看详情
    const viewDetail = () => {
      const selectedItems = invoiceList.value.filter(i => i.selected);
      
      // 校验选择条数
      if (selectedItems.length === 0) {
        alert('请选择一条记录');
        return;
      }
      if (selectedItems.length > 1) {
        alert('只能选择一条记录查看详情');
        return;
      }
      
      const invoice = selectedItems[0];
      console.log('查看发票详情, ID:', invoice.id);
      
      // 打开模态框
      detailModal.visible = true;
      detailLoading.value = true;
      invoiceDetail.value = null;
      
      // 调用后端接口查询详情
      axios({
        url: '/api/invoice/query_invoice_detail',
        method: 'get',
        params: { id: invoice.id }
      }).then(res => {
        console.log('详情响应数据:', res.data);
        detailLoading.value = false;
        
        if (res.data && res.data.code === 200) {
          invoiceDetail.value = res.data.data;
          console.log('发票详情:', invoiceDetail.value);
        } else {
          console.error('查询详情失败:', res.data.message || '未知错误');
          alert('查询详情失败: ' + (res.data.message || '请检查服务器连接'));
          detailModal.visible = false;
        }
      }).catch(err => {
        detailLoading.value = false;
        console.error('请求失败:', err);
        alert('请求失败，请检查网络连接');
        detailModal.visible = false;
      });
      
      // 添加body的modal-open类
      setTimeout(() => {
        document.body.classList.add('modal-open');
      }, 10);
    };
    
    // 关闭详情模态框
    const closeDetailModal = () => {
      detailModal.visible = false;
      invoiceDetail.value = null;
      setTimeout(() => {
        document.body.classList.remove('modal-open');
      }, 200);
    };

    // 发票阅览
    const viewInvoice = () => {
      const selectedItems = invoiceList.value.filter(i => i.selected);
      
      // 校验选择条数
      if (selectedItems.length === 0) {
        alert('请选择一条记录');
        return;
      }
      if (selectedItems.length > 1) {
        alert('只能选择一条记录查看发票图片');
        return;
      }
      
      const invoice = selectedItems[0];
      console.log('查看发票图片, ID:', invoice.id);
      
      // 打开模态框
      imageModal.visible = true;
      imageLoading.value = true;
      invoiceImage.value = null;
      
      // 调用后端接口查询图片
      axios({
        url: '/api/invoice/query_invoice_image',
        method: 'get',
        params: { id: invoice.id }
      }).then(res => {
        console.log('图片响应数据:', res.data);
        imageLoading.value = false;
        
        if (res.data && res.data.code === 200) {
          invoiceImage.value = res.data.data;
          console.log('发票图片:', invoiceImage.value);
        } else {
          console.error('查询图片失败:', res.data.message || '未知错误');
          alert('查询图片失败: ' + (res.data.message || '请检查服务器连接'));
          imageModal.visible = false;
        }
      }).catch(err => {
        imageLoading.value = false;
        console.error('请求失败:', err);
        alert('请求失败，请检查网络连接');
        imageModal.visible = false;
      });
      
      // 添加body的modal-open类
      setTimeout(() => {
        document.body.classList.add('modal-open');
      }, 10);
    };
    
    // 关闭图片模态框
    const closeImageModal = () => {
      imageModal.visible = false;
      invoiceImage.value = null;
      setTimeout(() => {
        document.body.classList.remove('modal-open');
      }, 200);
    };
    
    // 图片加载错误处理
    const handleImageError = (event) => {
      console.error('图片加载失败');
      event.target.src = 'data:image/svg+xml,%3Csvg xmlns="http://www.w3.org/2000/svg" width="200" height="200"%3E%3Crect fill="%23f8f9fa" width="200" height="200"/%3E%3Ctext fill="%236c757d" font-family="sans-serif" font-size="14" x="50%25" y="50%25" text-anchor="middle" dy=".3em"%3E图片加载失败%3C/text%3E%3C/svg%3E';
      event.target.style.maxHeight = '200px';
    };

    // 导出数据
    const exportData = () => {
      const selectedItems = invoiceList.value.filter(i => i.selected);
      
      // 校验选择条数
      if (selectedItems.length === 0) {
        alert('请至少选择一条记录进行导出');
        return;
      }
      
      // 提取发票ID数组
      const invoice_ids = selectedItems.map(item => item.id);
      console.log('导出发票IDs:', invoice_ids);
      
      // 显示加载提示
      if (confirm(`确认导出 ${selectedItems.length} 条发票数据吗？`)) {
        loading.value = true;
        
        // 调用后端接口导出
        axios({
          url: '/api/invoice/export_invoice_excel',
          method: 'post',
          data: { invoice_ids: invoice_ids },
          responseType: 'blob'  // 重要：设置响应类型为blob
        }).then(res => {
          console.log('导出响应:', res);
          loading.value = false;
          
          // 创建blob URL并触发下载
          const blob = new Blob([res.data], {
            type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
          });
          const url = window.URL.createObjectURL(blob);
          const link = document.createElement('a');
          link.href = url;
          link.download = 'invoice_output.xlsx';
          document.body.appendChild(link);
          link.click();
          document.body.removeChild(link);
          window.URL.revokeObjectURL(url);
          
          alert(`成功导出 ${selectedItems.length} 条发票数据`);
          console.log('导出成功');
        }).catch(err => {
          loading.value = false;
          console.error('导出失败:', err);
          
          // 处理错误响应
          if (err.response && err.response.data) {
            // 如果是blob类型的错误响应，需要转换为文本
            const reader = new FileReader();
            reader.onload = function() {
              try {
                const error = JSON.parse(reader.result);
                alert('导出失败: ' + (error.message || '请检查服务器连接'));
              } catch (e) {
                alert('导出失败，请检查网络连接');
              }
            };
            reader.readAsText(err.response.data);
          } else {
            alert('导出失败，请检查网络连接');
          }
        });
      }
    };

    // 格式化金额
    const formatMoney = (value) => {
      if (value === null || value === undefined) return '-';
      return '￥' + parseFloat(value).toFixed(2);
    };

    // 格式化日期
    const formatDate = (dateStr) => {
      if (!dateStr) return '-';
      // 处理ISO格式日期
      const date = new Date(dateStr);
      if (isNaN(date.getTime())) return dateStr;
      return date.toISOString().split('T')[0];
    };

    // 页面加载时调用
    onMounted(() => {
      queryList();
    });

    // 返回外部使用的数据状态和操作
    return {
      invoiceList,
      loading,
      selectAll,
      searchForm,
      detailModal,
      detailLoading,
      invoiceDetail,
      imageModal,
      imageLoading,
      invoiceImage,
      queryList,
      onSearch,
      resetSearch,
      toggleAll,
      viewDetail,
      closeDetailModal,
      viewInvoice,
      closeImageModal,
      handleImageError,
      exportData,
      formatMoney,
      formatDate
    };
  }
});

app.mount('#app');
</script>

<style>
.table-hover tbody tr:hover {
  background-color: #f8f9fa;
}

.btn-sm {
  padding: 0.25rem 0.5rem;
  font-size: 0.875rem;
}

.text-end {
  text-align: right;
}

.spinner-border {
  width: 2rem;
  height: 2rem;
}
</style>

</body>
{% endverbatim %}
</html>